<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form'
import type { VxeTableGridOptions } from '#/adapter/vxe-table'

import { computed, ref, markRaw } from 'vue'
import { Page, useVbenModal } from '@vben/common-ui'
import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { getErpWarehouseList, doErpWarehouseDelete } from '#/api/erpwarehouse'
import { Button, message, Popconfirm } from 'ant-design-vue'

import { AntPlusOutlined, AntDeleteOutlined } from '@vben/icons'

import Form from './modules/form.vue'
import TwoFields from '#/views/backend/modules/two-fields.vue'

interface RowType {
  [key: string]: any
}

// 获取选中的行数据
const selectedRows = ref<any>([])

// 删除按钮是否禁用
const isDisabledDelete = computed(() => {
  return selectedRows.value.length <= 0
})

const defaultSort: { field: string; order: '' | 'asc' | 'desc' | null } = {
  field: 'id',
  order: 'desc',
}

// 获取选中行的ID数组
const getSelectionIds = () => {
  return selectedRows.value.map((row: any) => row.id)
}

const formOptions: VbenFormProps = {
  wrapperClass: 'grid-cols-5',
  schema: [
    {
      component: markRaw(TwoFields),
      fieldName: 'id',
      disabledOnChangeListener: false,
      label: '仓库ID',
      operator: 'RANGE',
      valueToString: true,
      componentProps: {
        allowClear: true,
        placeholder: '范围筛选',
      },
    },
    {
      component: 'Input',
      fieldName: 'WarehouseCode',
      label: '仓库编码',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'WarehouseName',
      label: '仓库名称',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'Contact',
      label: '联系人',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'Tel',
      label: '联系电话',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'Address',
      label: '地址',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Select',
      fieldName: 'IsDefault',
      label: '是否默认',
      operator: '=',
      componentProps: {
        allowClear: true,
        options: [
          {
            label: '是',
            value: 1,
          },
          {
            label: '否',
            value: 0,
          },
        ],
        placeholder: '请选择',
      },
    },
  ],
  showCollapseButton: true,
  collapsed: true,
  submitOnChange: false,
  submitOnEnter: true,
}

const gridOptions: VxeTableGridOptions<RowType> = {
  border: true,
  checkboxConfig: {
    highlight: true,
    reserve: true,
    showReserveStatus: true,
  },
  rowConfig: {
    useKey: true,
    keyField: 'id',
    isHover: true,
  },
  columnConfig: {
    useKey: true,
  },
  columns: [
    { type: 'checkbox', width: 70, fixed: 'left' },
    { field: 'id', width: 70, title: 'ID', fixed: 'left', sortable: true },
    { field: 'WarehouseId', width: 100, title: '仓库ID' },
    { field: 'WarehouseCode', width: 120, title: '仓库编码' },
    { field: 'WarehouseName', width: 150, title: '仓库名称', fixed: 'left' },
    { field: 'Tel', width: 120, title: '联系电话' },
    { field: 'Contact', width: 120, title: '联系人' },
    { field: 'Fax', width: 120, title: '传真' },
    { field: 'ZipCode', width: 100, title: '邮编' },
    { field: 'RegionId', width: 100, title: '区域ID' },
    { field: 'Address', width: 200, title: '地址' },
    { field: 'IsDefault', width: 100, title: '是否默认', slots: { default: 'IsDefault' } },
    { field: 'CreateTime', width: 160, title: '创建时间', sortable: true },
    { field: 'CreateUserName', width: 120, title: '创建人' },
    { field: 'UpdateTime', width: 160, title: '更新时间', sortable: true },
    {
      field: 'operation',
      fixed: 'right',
      slots: { default: 'operation' },
      title: '操作',
      width: 150,
    },
  ],
  exportConfig: {},
  height: 'auto',
  keepSource: true,
  pagerConfig: {
    pageSize: 20,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page, sort }) => {
        const search = await gridApi.formApi.getFiltersValues()
        const res = await getErpWarehouseList({
          page: page.currentPage,
          limit: page.pageSize,
          search,
          order: sort.field && sort.order ? `${sort.field},${sort.order}` : `${defaultSort.field},${defaultSort.order}`,
        })

        return {
          items: res.list,
          total: res.total,
        }
      },
    },
    sort: true,
  },
  sortConfig: {
    defaultSort,
    remote: true,
  },
  toolbarConfig: {
    custom: true,
    export: true,
    refresh: true,
    resizable: true,
    search: true,
    zoom: true,
  },
  id: 'erpwarehouse_list',
  customConfig: {
    storage: true,
  },
}

// 处理新建操作
const handleCreate = () => {
  FormModalApi.setData({}).open()
}

// 处理编辑操作
const handleEdit = (row: any) => {
  FormModalApi.setData({
    info: row,
  }).open()
}

// 处理删除操作
const handleDelete = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要删除的数据')
    return
  }
  const hideLoading = message.loading({
    content: '删除',
    duration: 0,
    key: 'action_process_msg',
  })

  doErpWarehouseDelete({ ids: getSelectionIds() })
    .then(() => {
      message.success({
        content: '删除成功',
        key: 'action_process_msg',
      })
      gridApi.query()
    })
    .catch(() => {
      hideLoading()
    })
}

// 刷新数据
const fetchData = async () => {
  gridApi.reload()
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents: {
    checkboxChange: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    },
    checkboxAll: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    },
  },
})

const [FormModal, FormModalApi] = useVbenModal({
  connectedComponent: Form,
})
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <Button class="mr-2" type="primary" @click="handleCreate()">
          <AntPlusOutlined />
          新建
        </Button>

        <Popconfirm
          title="确认删除"
          :disabled="isDisabledDelete"
          :description="`确定要删除选中的 ${selectedRows.length} 条数据吗？此操作不可恢复。`"
          ok-text="确认"
          cancel-text="取消"
          @confirm="handleDelete"
          @cancel="() => {}"
        >
          <Button class="mr-2" type="primary" danger :disabled="isDisabledDelete">
            <AntDeleteOutlined />
            删除
          </Button>
        </Popconfirm>
      </template>

      <template #IsDefault="{ row }">
        <span v-if="row.IsDefault === 1" class="text-green-500">是</span>
        <span v-else class="text-gray-500">否</span>
      </template>

      <template #operation="{ row }">
        <Button class="mr-2" type="primary" size="small" @click.stop="handleEdit(row)">编辑</Button>
      </template>
    </Grid>
    <FormModal @fetch-data="fetchData" />
  </Page>
</template>
